/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tecpizza;

import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import negocio.Sabor;

/**
 *
 * @author tecnico
 */
public class TelaSabores extends javax.swing.JFrame {

    /**
     * Creates new form sabores
     */
    public TelaSabores() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextFieldNome = new javax.swing.JTextField();
        jLabelNome = new javax.swing.JLabel();
        jLabelIngrediente = new javax.swing.JLabel();
        jRadioButtonSalgado = new javax.swing.JRadioButton();
        jRadioButtonDoce = new javax.swing.JRadioButton();
        jButtonSalvar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableSabores = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaIngredientes = new javax.swing.JTextArea();
        jButtonAlterar = new javax.swing.JButton();
        jTextCodigo = new javax.swing.JTextField();
        jLabelCadSabores = new javax.swing.JLabel();
        jCheckBoxAtivo = new javax.swing.JCheckBox();
        jLabelAtivo = new javax.swing.JLabel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setTitle("Cadastro de sabores");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jTextFieldNome.setToolTipText("Insira o nome do sabor");

        jLabelNome.setText("Nome:");

        jLabelIngrediente.setText("Ingredientes:");

        buttonGroup1.add(jRadioButtonSalgado);
        jRadioButtonSalgado.setText("Salgado");

        buttonGroup1.add(jRadioButtonDoce);
        jRadioButtonDoce.setText("Doce");

        jButtonSalvar.setText("Salvar");
        jButtonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarActionPerformed(evt);
            }
        });

        jTableSabores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nome", "Ingredientes", "Tipo", "Ativo", "Alterar", "Excluir"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableSabores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableSaboresMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTableSabores);
        jTableSabores.getColumnModel().getColumn(0).setResizable(false);
        jTableSabores.getColumnModel().getColumn(1).setResizable(false);
        jTableSabores.getColumnModel().getColumn(2).setResizable(false);
        jTableSabores.getColumnModel().getColumn(3).setResizable(false);
        jTableSabores.getColumnModel().getColumn(4).setResizable(false);
        jTableSabores.getColumnModel().getColumn(5).setResizable(false);
        jTableSabores.getColumnModel().getColumn(6).setResizable(false);

        jTextAreaIngredientes.setColumns(20);
        jTextAreaIngredientes.setRows(5);
        jScrollPane3.setViewportView(jTextAreaIngredientes);

        jButtonAlterar.setText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });

        jLabelCadSabores.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
        jLabelCadSabores.setText("Cadastro de Sabores");

        jLabelAtivo.setText("Ativo:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(272, 272, 272)
                        .addComponent(jLabelCadSabores))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 717, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(216, 216, 216)
                                .addComponent(jButtonAlterar)
                                .addGap(56, 56, 56)
                                .addComponent(jButtonSalvar))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(96, 96, 96)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabelAtivo)
                                        .addGap(18, 18, 18)
                                        .addComponent(jCheckBoxAtivo))
                                    .addComponent(jLabelIngrediente)
                                    .addComponent(jLabelNome))
                                .addGap(42, 42, 42)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jRadioButtonSalgado)
                                        .addGap(40, 40, 40)
                                        .addComponent(jRadioButtonDoce))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jTextCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE))))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabelCadSabores)
                .addGap(18, 18, 18)
                .addComponent(jTextCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelNome)
                    .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addComponent(jLabelIngrediente))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jRadioButtonSalgado)
                        .addComponent(jRadioButtonDoce))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabelAtivo)
                        .addComponent(jCheckBoxAtivo)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSalvar)
                    .addComponent(jButtonAlterar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed
        if(jTextFieldNome.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Nome deve ser preenchido!");
            return;
        }
        if(jTextAreaIngredientes.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Ingrediente deve ser preenchido!");
            return;
        }
        if(jRadioButtonSalgado.isSelected()==false && jRadioButtonDoce.isSelected()==false){
        jRadioButtonSalgado.getText().equals("");
        jRadioButtonDoce.getText().equals("");
        JOptionPane.showMessageDialog(null, "Sabor deve ser selecionado!");
        return;
    }
        
    Sabor sabor =new Sabor();
    sabor.setNome(jTextFieldNome.getText());
    sabor.setIngredientes(jTextAreaIngredientes.getText());
    sabor.setTipo(jRadioButtonSalgado.isSelected());
    sabor.salvar();
    
    JOptionPane.showMessageDialog(null, "Sabor cadastrado com Sucesso!");   
    jTextFieldNome.setText("");
    jTextAreaIngredientes.setText("");
    jCheckBoxAtivo.setSelected(false);
    jRadioButtonDoce.setSelected(false);
    jRadioButtonSalgado.setSelected(false);
       
    }//GEN-LAST:event_jButtonSalvarActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
        
        jButtonAlterar.setVisible(false);
        jButtonSalvar.setVisible(true);
        jTextCodigo.setVisible(false);
        jLabelAtivo.setVisible(false);
        jCheckBoxAtivo.setVisible(false);
        atualizaTabela();
    }//GEN-LAST:event_formWindowActivated

    private void jTableSaboresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableSaboresMouseClicked
        
        Sabor sabor = new Sabor();
        if(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 5)==true){
            jTextCodigo.setText(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 0).toString());
            jTextFieldNome.setText(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 1).toString());
            jTextAreaIngredientes.setText(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 2).toString());
            jCheckBoxAtivo.setSelected(Boolean.parseBoolean(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 4).toString()));
            jButtonAlterar.setVisible(true);
            jButtonSalvar.setVisible(false);
            jLabelAtivo.setVisible(true);
            jCheckBoxAtivo.setVisible(true);
            jRadioButtonDoce.setEnabled(false);
            jRadioButtonSalgado.setEnabled(false);
            jTableSabores.getModel().setValueAt(false, jTableSabores.getSelectedRow() ,5);
        }
        else
        if(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 6)==true){
            if(JOptionPane.showConfirmDialog(null, "Deseja excluir este sabor " + 
                    jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow(), 1).toString() + " ? ", 
                  //  "Confirma exclusão", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
             "Confirma Exclusão",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
               if (sabor.podeExcluir(Integer.parseInt(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow() ,0).toString()))){
                    sabor.excluir(Integer.parseInt(jTableSabores.getModel().getValueAt(jTableSabores.getSelectedRow() ,0).toString()));
                    JOptionPane.showMessageDialog(null,"Registro excluído com sucesso.");
               }else{
                   JOptionPane.showMessageDialog(null,"Este registro não pode ser excluído pois já foi utilizado em pedidos.");
               }
            }
        }
    }//GEN-LAST:event_jTableSaboresMouseClicked

    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        
        if(jTextFieldNome.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Preencha o campo Nome!");
            return;
        }
        if(jTextAreaIngredientes.getText().equals("")){
            JOptionPane.showMessageDialog(null, "Preencha o campo Ingredientes!");
            return;
        }
        
        Sabor sabor = new Sabor();
        sabor.setNome(jTextFieldNome.getText());
        sabor.setIngredientes(jTextAreaIngredientes.getText());
        sabor.setCodigo(Integer.parseInt(jTextCodigo.getText()));
        sabor.setAtivo(jCheckBoxAtivo.isSelected());
        sabor.alterar();
        
        JOptionPane.showMessageDialog(null, "Sabor alterado com sucesso!");
        jTextFieldNome.setText("");
        jTextAreaIngredientes.setText("");
        jCheckBoxAtivo.setSelected(false);
        //teste
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void atualizaTabela(){
        DefaultTableModel tTabela = (DefaultTableModel) jTableSabores.getModel();
        tTabela.setNumRows(0);
        Sabor sab = new Sabor();
        
        List<Sabor> sabores = sab.getAll();
        if (sabores!=null){
            for (int linha = 0; linha < sabores.size(); linha++)
            {
                Sabor sabor = sabores.get(linha);

                tTabela.addRow(new Object[]{1});

                jTableSabores.setValueAt(sabor.getCodigo(), linha, 0);
                jTableSabores.setValueAt(sabor.getNome(), linha, 1);
                jTableSabores.setValueAt(sabor.getIngredientes(), linha, 2);
                jTableSabores.setValueAt(sabor.isTipoTela(), linha, 3);
                jTableSabores.setValueAt(sabor.isAtivo(), linha, 4);
            }
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaSabores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaSabores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaSabores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaSabores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaSabores().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonSalvar;
    private javax.swing.JCheckBox jCheckBoxAtivo;
    private javax.swing.JLabel jLabelAtivo;
    private javax.swing.JLabel jLabelCadSabores;
    private javax.swing.JLabel jLabelIngrediente;
    private javax.swing.JLabel jLabelNome;
    private javax.swing.JRadioButton jRadioButtonDoce;
    private javax.swing.JRadioButton jRadioButtonSalgado;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTableSabores;
    private javax.swing.JTextArea jTextAreaIngredientes;
    private javax.swing.JTextField jTextCodigo;
    private javax.swing.JTextField jTextFieldNome;
    // End of variables declaration//GEN-END:variables
}
